

FROM node:22.14.0  AS base

# Install dependencies only when needed
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
# RUN apk add --no-cache libc6-compat
WORKDIR /app
RUN mkdir -p /app && ls -la /app

# 基于首选包管理器安装依赖项
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* .npmrc* ./
# 启用 Corepack 并安装指定版本的 Yarn
RUN corepack enable && corepack prepare yarn@3.6.1 --activate
# RUN echo '{"installConfig":{"pnp":false}}' > .yarnrc
# 强制生成 node_modules 文件夹
RUN echo 'nodeLinker: node-modules' > .yarnrc.yml
# RUN npm install -g yarn
# RUN \
#   if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
#   elif [ -f package-lock.json ]; then npm ci; \
#   elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \
#   else echo "Lockfile not found." && exit 1; \
#   fi

RUN yarn install


# 仅在需要时重新构建源代码
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN yarn build 

# 新增压缩阶段
FROM base AS compressor
WORKDIR /app
COPY --from=builder /app/.next/static ./.next/static
# 对静态资源进行gzip压缩
RUN find .next/static -type f \( -name '*.js' -o -name '*.css' -o -name '*.html' \) -exec gzip -k -9 {} \;

# Next.js 收集关于一般使用的完全匿名的遥测数据.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED=1

# RUN \
#   if [ -f yarn.lock ]; then yarn run build; \
#   elif [ -f package-lock.json ]; then npm run build; \
#   elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \
#   else echo "Lockfile not found." && exit 1; \
#   fi

# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED=1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# 复制压缩后的文件
COPY --from=compressor /app/.next/static ./.next/static

COPY --from=builder /app/public ./public
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER root

EXPOSE 3000

ENV PORT=3000

ENV HOSTNAME="0.0.0.0"
# 生成容器的时候执行的命令
# CMD ["yarn", "serve"]
CMD ["node", "server.js"]